#!/bin/bash

# 中国大陆需要安装脚本额外配置镜像地址以及低版本的 NodeJS 环境
mcsmanager_install_path="/opt/mcsmanager"
mcsmanager_download_addr="https://cdn.imlazy.ink:233/files/mcsmanager_linux_release.tar.gz"
package_name="mcsmanager_linux_release.tar.gz"
node="v16.20.2"
arch=$(uname -m)

if [ "$(id -u)" -ne 0]; then
  echo "This script must be run as root. Please use \"sudo bash\" instead."
  exit 1
fi

printf "\033c"

echo_cyan() {
  printf '\033[1;36m%b\033[0m\n' "$@"
}
echo_red() {
  printf '\033[1;31m%b\033[0m\n' "$@"
}

echo_green() {
  printf '\033[1;32m%b\033[0m\n' "$@"
}

echo_cyan_n() {
  printf '\033[1;36m%b\033[0m' "$@"
}

echo_yellow() {
  printf '\033[1;33m%b\033[0m\n' "$@"
}

# script info
echo_cyan "+--------------------------------------------------------------
| MCSManager 安装脚本 (MCSManager Installer)
+--------------------------------------------------------------
"

Red_Error() {
  echo '================================================='
  printf '\033[1;31;40m%b\033[0m\n' "$@"
  echo '================================================='
  exit 1
}

Install_Node() {
  echo_cyan_n "[+] Install Node.JS environment...\n"
  echo_cyan_n "[+] Removing old installation directory...\n"
  rm -irf "$node_install_path"
  echo_green "[✔] Done\n"

  cd /opt || Red_Error "[x] Failed to enter /opt"

  echo_cyan_n "[+] Removing old node tarball...\n"
  rm -rf "node-$node-linux-$arch.tar.gz"
  echo_green "[✔] Done\n"

  # From https://nodejs.org/
  # wget "https://nodejs.org/dist/$node/node-$node-linux-$arch.tar.gz" || Red_Error "[x] Failed to download node release"

  echo_cyan_n "[+] Downloading Node.js release from npmmirror...\n"
  # From https://registry.npmmirror.com/
  wget "https://registry.npmmirror.com/-/binary/node/$node/node-$node-linux-$arch.tar.gz" && echo_green "[✔] Done\n"|| Red_Error "[x] Failed to download node release"

  echo_cyan_n "[+] Extracting Node.js tarball...\n"
  tar -zxf "node-$node-linux-$arch.tar.gz" && echo_green "[✔] Done\n"|| Red_Error "[x] Failed to untar node"


  rm -rf "node-$node-linux-$arch.tar.gz"

  echo_cyan_n "[+] Creating symbolic links...\n"
  ln -sf "$node_install_path"/bin/node /bin/node
  ln -sf "$node_install_path"/bin/npm /bin/npm
  ln -sf "$node_install_path"/bin/npx /bin/npx
  echo_green "[✔] Done\n"

  if [[ -f /bin/node ]] && [[ "$(/bin/node -v)" == "$node" ]]; then
    echo_green "[✔] Node installation successful!"
  else
    Red_Error "[x] Node installation failed!"
  fi

  echo
  echo_yellow "=============== Node.JS Version ==============="
  echo_yellow " node: $("$node_install_path"/bin/node -v)"
  echo_yellow " npm: v$(env "$node_install_path"/bin/node "$node_install_path"/bin/npm -v)"
  echo_yellow "=============== Node.JS Version ==============="
  echo

  sleep 3
}
Install_MCSManager() {
  echo_cyan "[+] Install MCSManager..."
  echo_cyan_n "[+] Removing old installation directory...\n"
  rm -rf "${mcsmanager_install_path}"
  echo_green "[✔] Done\n"

  #mkdir -p "${mcsmanager_install_path}" || Red_Error "[x] Failed to create ${mcsmanager_install_path}"

  # cd $HOME/mcsm/mcsmanager
  cd "/opt" || Red_Error "[x] Failed to enter /opt"

  # download MCSManager release
  wget "${mcsmanager_download_addr}" -O "${package_name}" || Red_Error "[x] Failed to download MCSManager"
  tar -zxf ${package_name} -o || Red_Error "[x] Failed to untar ${package_name}"
  rm -rf "${mcsmanager_install_path}/${package_name}"

  # echo "[→] cd daemon"
  cd "${mcsmanager_install_path}/daemon" || Red_Error "[x] Failed to enter ${mcsmanager_install_path}/daemon"

  echo_cyan "[+] Install MCSManager-Daemon dependencies..."
  env "$node_install_path"/bin/node "$node_install_path"/bin/npm install --registry=https://registry.npmmirror.com --production --no-fund --no-audit &>/dev/null && echo_green "[✔] Done\n"|| Red_Error "[x] Failed to npm install in ${mcsmanager_install_path}/daemon"

  # echo "[←] cd .."
  cd "${mcsmanager_install_path}/web" || Red_Error "[x] Failed to enter ${mcsmanager_install_path}/web"

  echo_cyan "[+] Install MCSManager-Web dependencies..."
  env "$node_install_path"/bin/node "$node_install_path"/bin/npm install --registry=https://registry.npmmirror.com --production --no-fund --no-audit &>/dev/null && echo_green "[✔] Done\n"|| Red_Error "[x] Failed to npm install in ${mcsmanager_install_path}/web"

  echo
  echo_yellow "=============== MCSManager ==============="
  echo_green "Daemon: ${mcsmanager_install_path}/daemon"
  echo_green "Web: ${mcsmanager_install_path}/web"
  echo_yellow "=============== MCSManager ==============="
  echo
  echo_green "[✔] MCSManager installation success!"

  chmod -R 755 "$mcsmanager_install_path"

  sleep 3
}

Create_startup_script() {
  echo_cyan "[+] Create MCSManager startup script..."

  script_path="$mcsmanager_install_path/start_mcsmanager.sh"
  echo '#!/bin/bash

echo_cyan() {
  printf "\033[1;36m%b\033[0m\n" "$@"
}
echo_red() {
  printf "\033[1;31m%b\033[0m\n" "$@"
}
echo_green() {
  printf "\033[1;32m%b\033[0m\n" "$@"
}
echo_cyan_n() {
  printf "\033[1;36m%b\033[0m" "$@"
}
echo_yellow() {
  printf "\033[1;33m%b\033[0m\n" "$@"
}

# 切换到工作目录
cd /opt/mcsmanager || exit

# 定义日志文件路径
LOG_DIR="$HOME/mcsm/logs"
mkdir -p "$LOG_DIR"

# 定义各个服务的日志文件
DAEMON_LOG="$LOG_DIR/mcsm_daemon.log"
WEB_LOG="$LOG_DIR/mcsm_web.log"

# 启动或重启 screen 会话并运行脚本
start_screen_session() {
    SESSION_NAME=$1
    SCRIPT=$2
    LOG_FILE=$3

    # 如果会话已经存在，则先杀死会话
    screen -ls | grep -w $SESSION_NAME > /dev/null
    if [ $? -eq 0 ]; then
        echo_yellow "[!] 正在杀死已存在的会话: $SESSION_NAME"
        screen -S $SESSION_NAME -X quit
        screen -wipt $SESSION_NAME
    fi

    # 创建新的会话并运行脚本
    echo "[+] 正在启动新会话: $SESSION_NAME"
    screen -dmS $SESSION_NAME /bin/bash -c "exec > >(tee $LOG_FILE) 2>&1; $SCRIPT"
}

# 启动 daemon 服务
start_screen_session "mcsm-daemon" "./start-daemon.sh" "$DAEMON_LOG"

# 启动 web 服务
start_screen_session "mcsm-web" "./start-web.sh" "$WEB_LOG"

echo_yellow "==============================================================="
echo_green "所有服务均已启动，欢迎使用 MCSManager ！"
echo_yellow " "
echo_cyan_n "主控网页访问地址:        "
echo_yellow "http://<Your IP>:23333  (Browser)"
echo_cyan_n "被控守护进程地址:          "
echo_yellow "ws://<Your IP>:24444    (Cluster)"
echo_yellow " "
echo_cyan "面板指令:"
echo_cyan "查看状态：screen -ls"
echo_cyan "停止面板：stop_mcsmanager"
echo_yellow " "
echo_yellow "请查看日志文件以获取更多信息: ~/mcsm/log/"
echo_red "默认情况下，你必须开放 23333 和 24444 端口才能确保面板工作正常！"
echo_yellow "==============================================================="' > $script_path && echo_green "[✔] Done\n" && echo -e "\033[0;32m[+] Startup script created at: $script_path\033[0m"|| Red_Error "[x] Failed to Create MCSManager startup script at $script_path"
  # 赋予脚本可执行权限
  echo_cyan_n "[+] Setting Startup script as executable...\n"
  chmod +x $script_path && echo_green "[✔] Done\n"|| Red_Error "[x] Failed"

  echo_cyan_n "[+] Create Startup script at: system_Bin...\n"
  ln -sf "$script_path" "/bin/start_mcsmanager"&& echo_green "[+] [✔] Done\n"|| Red_Error "[x] Failed"

  echo_cyan "[+] Create MCSManager stop script...\n"

  stopscript_path="$mcsmanager_install_path/stop_mcsmanager.sh"
  echo '#!/bin/bash

echo_cyan() {
  printf "\033[1;36m%b\033[0m\n" "$@"
}
echo_red() {
  printf "\033[1;31m%b\033[0m\n" "$@"
}
echo_green() {
  printf "\033[1;32m%b\033[0m\n" "$@"
}
echo_cyan_n() {
  printf "\033[1;36m%b\033[0m" "$@"
}
echo_yellow() {
  printf "\033[1;33m%b\033[0m\n" "$@"
}

screen -S mcsm-web -X quit && echo_cyan "[+] close mcsm-web"
screen -S mcsm-daemon -X quit && echo_cyan "[+] close mcsm-daemon"

echo_yellow "==============================================================="
echo_green "所有服务均已停止"
echo_yellow " "
echo_yellow "请查看日志文件以获取更多信息: $HOME/mcsm/log/"
echo_yellow "再会！！！"
echo_yellow "==============================================================="' > $stopscript_path && echo_green "[✔] Done\n" && echo -e "\033[0;32m[+] Stop script created at: $stopscript_path\033[0m"|| Red_Error "[x] Failed to Create MCSManager stop script at $stopscript_path"

  # 赋予脚本可执行权限
  echo_cyan_n "[+] Setting Stop script as executable...\n"
  chmod +x $stopscript_path && echo_green "[✔] Done\n"

  echo_cyan_n "[+] Create Stop script at: system_Bin...\n"
  ln -sf "$stopscript_path" "/bin/stop_mcsmanager"&& echo_green "[✔] Done\n"

  sleep 2

  printf "\n\n\n\n"

  echo_yellow "==============================================================="
  echo_green "安装完成，欢迎使用 MCSManager ！"
  echo_yellow " "
  echo_cyan_n "主控网页访问地址:        "
  echo_yellow "http://<Your IP>:23333  (Browser)"
  echo_cyan_n "被控守护进程地址:          "
  echo_yellow "ws://<Your IP>:24444    (Cluster)"
  echo_red "默认情况下，你必须开放 23333 和 24444 端口才能确保面板工作正常！"
  echo_yellow " "
  echo_cyan "面板开关指令:"
  echo_cyan "启动：start_mcsmanager"
  echo_cyan "停止：stop_mcsmanager"
  echo_yellow " "
  echo_green "官方文档: https://docs.mcsmanager.com/"
#   echo_green
  echo_red "该脚本由moze_sz修改以适配proot"
  echo_yellow "==============================================================="
}

# Environmental inspection
if [[ "$arch" == aarch64 ]]; then
  arch=arm64
  #echo "[-] 64-bit ARM architecture detected"
elif [[ $arch == arm ]]; then
  arch=armv7l
  #echo "[-] 32-bit ARM architecture detected"
else
  Red_Error "[x] Sorry, this architecture is not supported yet!\n[x]Please try to install manually: https://github.com/MCSManager/MCSManager#linux"
fi

# Define the variable Node installation directory
node_install_path="/opt/node-$node-linux-$arch"

# Check network connection
echo_cyan "[-] Architecture: $arch"

# Install related software
echo_cyan_n "[+] Installing dependent software (git, tar, wget, screen)... \n"
if [[ -x "$(command -v yum)" ]]; then
  yum update -y
  yum install -y epel-release
  yum install -y git tar wget screen
elif [[ -x "$(command -v apt-get)" ]]; then
  apt-get update -y
  apt-get upgrade -y
  apt-get install -y git tar wget screen
# elif [[ -x "$(command -v pacman)" ]]; then
#   pacman -S --noconfirm git tar wget
# elif [[ -x "$(command -v zypper)" ]]; then
#   zypper --non-interactive install git tar wget
else
  echo_red "[!] Cannot find your package manager! You may need to install git, tar, screen and wget manually!"
fi

chmod 777 /run/screen

# Determine whether the relevant software is installed successfully
if [[ -x "$(command -v git)" && -x "$(command -v tar)" && -x "$(command -v wget)" && -x "$(command -v screen)" ]]; then
  echo_green "[✔] Success"
else
  Red_Error "[x] Failed to find git, tar and wget, please install them manually!"
fi

# Install the Node environment
Install_Node

# Install MCSManager
Install_MCSManager

# Create MCSManager Startup script
Create_startup_script
